const App = getApp()
const db = wx.cloud.database()
const _ = db.command
const pages = getCurrentPages()
let that
Page({

  /**
   * 页面的初始数据
   */
  data: {
    value: "",
    show: false,
    // 传值过来的课程id
    courseId: "",
    // 身份信息
    identityArray: [{
      name: '学生',
      id: 'Students'
    }, {
      name: '教师',
      id: 'Teachers'
    }, {
      name: '管理员',
      id: 'Administrator'
    }],
    // 课程详情
    courselist: "",
    // 课程成员列表
    courseMember: [],
    // 搜索使用的临时数组
    templist: [],
    // 移除成员的信息
    removeCourseInfo: [],

    // 添加搜索到的同学
    searchMember: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    that = this
    let courseId = JSON.parse(decodeURIComponent(options.passData))
    console.log('传值过来的课程id ', courseId);
    let UserInfo = App.cache.getUserInfo()
    console.log('获取用户信息:', UserInfo);
    delete UserInfo._id
    that.setData({
      UserInfo: UserInfo,
      courseId: courseId
    })
    that.getcourse()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },





  //打开操作面板
  showPopup(e) {
    console.log(e.currentTarget.dataset.account);
    let Infoaccount = e.currentTarget.dataset.account
    let courseMember = that.data.courselist.courseMember
    let removeCourseInfo = courseMember.filter(item => {
      return item.account === Infoaccount
    })
    console.log('有吗', removeCourseInfo[0]);
    this.setData({
      show: true,
      removeCourseInfo: removeCourseInfo[0]
    });
  },
  // 关闭操作面板
  onClose() {
    this.setData({
      show: false
    });
  },

  // 获取课程详情
  getcourse() {
    App.toast.showLoading('加载中')
    db.collection('course').where({
        courseId: that.data.courseId
      })
      .get({
        success: function (res) {
          let courselist = res.data[0]
          console.log('获取该课程', courselist)
          // 根据身份id获取对应的身份
          let identityobj = that.data.identityArray
          for (let i = 0; i < courselist.courseMember.length; i++) {
            let obj = identityobj.find(function (x) {
              return courselist.courseMember[i].identityId === x.id
            })
            courselist.courseMember[i].identityId = obj.name
          }
          that.setData({
            courselist: courselist,
            courseMember: courselist.courseMember,
            templist: courselist.courseMember
          })
          App.toast.hideLoading()
        }
      })
    App.toast.hideLoading()
  },
  // 搜索成员
  searchCourseMember(e) {
    let key = e.detail.toLowerCase();
    console.log(key);
    let list = that.data.templist;
    let newMember = []
    for (let i = 0; i < list.length; i++) {
      let listname = list[i].nickName.toLowerCase();
      if (listname.search(key) != -1) {
        newMember.push(list[i])
      }
    }
    console.log('筛选后:', newMember);
    that.setData({
      courseMember: newMember
    })
  },
  // 将同学移出课程
  removeCourseInfo(e) {
    console.log(e.currentTarget.dataset.account);
    let account = e.currentTarget.dataset.account
    wx.showModal({
      title: '提示',
      content: '确定将此同学移出班级吗',
      success(res) {
        if (res.confirm) {
          that.removeMember(account)
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  // 移除成员
  removeMember(e) {
    console.log(e);
    let accountkey = e
    if (accountkey === that.data.UserInfo.account) {
      App.toast.showToast('不可以移出自己', 'none')
    } else {
      App.toast.showLoading('加载中')
      db.collection('course').doc(that.data.courselist._id).update({
        data: {
          courseMember: _.pull({
            account: _.eq(accountkey),
          })
        },
        success: function (res) {
          console.log(res)
          // 同时将这名成员从课程社区中清除
          db.collection('chat-msg').where({
            ChatCommunityId: 'chat' + that.data.courselist.courseId
          }).update({
            data: {
              members: _.pull({
                account: _.eq(accountkey),
              })
            },
            success: function (res) {
              App.toast.hideLoading()
              App.toast.showToast('移出成功', 'none')
              that.onClose()
              that.getcourse()
            }
          })
        }
      })
    }

  },

  // 同步绑定班级的成员
  Synchronization() {
    // 根据班级id获取班级详情
    if (that.data.courselist.class.classId == null) {
      App.toast.showToast('请先绑定班级', "error")
      return
    }
    App.toast.showLoading('加载中')
    db.collection('myclass').where({
        myclassId: that.data.courselist.class.classId
      })
      .get({
        success: res => {
          console.log('获取班级详情', res.data[0])
          let classMember = res.data[0].list
          db.collection('course').where({
            courseId: that.data.courseId
          }).update({
            data: {
              courseMember: classMember
            },
            success: function (res) {
              App.toast.hideLoading()
              console.log('同步成功', res);
              that.getcourse()
              App.toast.showToast('成员同步成功')
            }
          })

        }
      })
  },

})